package com.czmh.etc.onlinepubsys.services.mingchuang.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.entity.mingchuang.EtcOrder;
import com.czmh.etc.onlinepubsys.entity.mingchuang.ExchangeCode;
import com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult;
import com.czmh.etc.onlinepubsys.maper.EtcUserMapper;
import com.czmh.etc.onlinepubsys.maper.mingchuang.CurrentContextMapper;
import com.czmh.etc.onlinepubsys.maper.mingchuang.ExchangeCodeMapper;
import com.czmh.etc.onlinepubsys.maper.mingchuang.MingchuangOrderMapper;
import com.czmh.etc.onlinepubsys.model.EtcDevice;
import com.czmh.etc.onlinepubsys.model.EtcUser;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcOrderService;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import lombok.experimental.var;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class EtcOrderServiceImpl implements IEtcOrderService {
    @Autowired
    private MingchuangOrderMapper mingchuangOrderMapper;
    @Autowired
    private CurrentContextMapper currentContextMapper;
    @Autowired
    private ExchangeCodeMapper exchangeCodeMapper;
    @Autowired
    private EtcUserMapper etcUserMapper;
    @Autowired
    private EtcOrderService orderService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void updateByOrderNo(String orderNo, String transactionId, Integer payState) {
        mingchuangOrderMapper.updateByOrderNo(orderNo, transactionId, payState);
    }

    @Override
    public void deleteUnpayOrder() {
        QueryWrapper<EtcOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("payState", 0);
        mingchuangOrderMapper.delete(wrapper);
    }

    @Override
    public EtcOrder getByOrderNo(String orderNo) {
        QueryWrapper<EtcOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("orderNo", orderNo);
        wrapper.eq("pay_mode", 1);
        return mingchuangOrderMapper.selectOne(wrapper);
    }

    @Override
    public EtcOrder getByProductSn(String productSn) {
        QueryWrapper<EtcOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("body", productSn);
        wrapper.eq("pay_mode", 1);
        List<EtcOrder> list = mingchuangOrderMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(list)){
            return list.get(0);
        }else{
            return null;
        }
    }

    @Override
    public EtcOrder getByProductSn(String productSn, Integer payMode) {
        QueryWrapper<EtcOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("body", productSn);
        wrapper.eq("pay_mode", payMode);
        List<EtcOrder> list = mingchuangOrderMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(list)){
            return list.get(0);
        }else{
            return null;
        }
    }

    @Override
    public void saveOrderAndContext(EtcOrder entity, CurrentContext ctx, String code) {
        Date now = new Date();
        entity.setCreateDate(now);
        mingchuangOrderMapper.insert(entity); //保存订单
        ctx.setType(entity.getType());
        ctx.setEtcUserType(entity.getEtcUserType());
        ctx.setChannel(entity.getChannel());
        currentContextMapper.insert(ctx); //记录上下文

        if (code != null) {
            //更新兑换码
            QueryWrapper<ExchangeCode> wrapper = new QueryWrapper<>();
            wrapper.eq("code", code);
            ExchangeCode exchangeCode = exchangeCodeMapper.selectOne(wrapper);

            exchangeCode.setExchangeTime(now);
            exchangeCode.setUserId(entity.getUserId());
            exchangeCode.setState(1); //已兑换
            exchangeCode.setDvId(entity.getDvId());
            exchangeCodeMapper.updateById(exchangeCode);
        }
        //发行方渠道配置选择
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("deleteFlag", "0");
        queryMap.put("productSn", entity.getBody());
        EtcDevice etcObuDTO = orderService.queryObject(queryMap);
        //产品发行方如果是西藏或者招商局统一走招商发行渠道
        if(etcObuDTO.getIssuerName().equalsIgnoreCase("西藏") || etcObuDTO.getIssuerName().equalsIgnoreCase("招商")){
            etcObuDTO.setIssuerName("招商");
            orderService.updateObject(etcObuDTO);
        }
        String issueName = redisUtil.getIssueName();
        if(issueName != null){
            etcObuDTO.setIssuerName(issueName);
            orderService.updateObject(etcObuDTO);
        }
    }

    @Override
    public JSONResult update(EtcOrder entity) {
        JSONResult result = new JSONResult();
        QueryWrapper<CurrentContext> ctxWrapper = new QueryWrapper<>();
        ctxWrapper.eq("user_id", entity.getUserId());
        ctxWrapper.eq("state", 1);
        ctxWrapper.eq("delete_flag", 0);
        ctxWrapper.eq("pay_mode", entity.getPayMode());
        CurrentContext ctx = currentContextMapper.selectOne(ctxWrapper);

        if (ctx == null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("当前用户不在流程中");
            return result;
        }
        String userId = entity.getUserId();
        //把订单对应的手机号码更新到用户信息当中
        EtcUser etcUser = etcUserMapper.getById(entity.getUserId());
        if(etcUser != null && StringUtils.isBlank(etcUser.getUser_phone()) && StringUtils.isBlank(etcUser.getUser_loginname())){
            etcUser.setUser_phone(entity.getPhone());
            etcUser.setUser_loginname(entity.getPhone());
            etcUserMapper.update(etcUser);
        }else {
            //如果用户存在且手机号码跟收货手机号码不同则根据收货手机号码创建新用户信息
            Map<String, Object> params = new HashMap<String, Object>(0);
            params.put("user_phone", entity.getPhone());
            EtcUser e = etcUserMapper.getAll(params).isEmpty() ? null : etcUserMapper.getAll(params).get(0);
            if(null == e){
                EtcUser user = new EtcUser();
                user.setUser_id(Sequence.getId());
                user.setCreate_time(new Date());
                user.setUpdate_time(new Date());
                user.setUser_sex(1);
                user.setUser_status(0);
                user.setUser_phone(entity.getPhone());
                user.setUser_loginname(entity.getPhone());
                // 1.初始化ETC用户信息
                etcUserMapper.insert(user);
                userId = user.getUser_id();
            }else if(!e.getUser_phone().equalsIgnoreCase(entity.getPhone())){
                result.setCode(JSONResult.FAIL);
                result.setMessage("该手机号码已经绑定其他ETC！");
                return result;
            }
        }

        QueryWrapper<EtcOrder> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("orderNo", ctx.getOrderNo());
        EtcOrder etcOrder = mingchuangOrderMapper.selectOne(orderWrapper);

        etcOrder.setVehPlate(entity.getVehPlate());
        etcOrder.setVehColor(entity.getVehColor());
        etcOrder.setProvince(entity.getProvince());
        etcOrder.setCity(entity.getCity());
        etcOrder.setRegion(entity.getRegion());
        etcOrder.setAddress(entity.getAddress());
        etcOrder.setConsignee(entity.getConsignee());
        etcOrder.setPhone(entity.getPhone());
        //更新订单用户信息
        etcOrder.setUserId(userId);
        mingchuangOrderMapper.updateById(etcOrder);

        return result;
    }

    @Override
    public void updateByObject(EtcOrder entity) {
        mingchuangOrderMapper.updateById(entity);
    }
}
